<?php
namespace src\controller;

use src\core\Database;
use src\models\Notice;

class NoticeCRUD {
    private $notice;

    public function __construct() {
        $db = new Database();
        $this->notice = new Notice($db->getConnection());
    }

    public function index() {
        $notices = $this->notice->getAll();
        require __DIR__ . '/../views/notice/list.view.php';
    }

    public function add() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
            $content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);
            $authorId = $_SESSION['user_id'] ?? 0;

            if ($this->notice->create($title, $content, $authorId)) {
                header('Location: index.php?c=notice&a=index');
                exit;
            }
        }
        require __DIR__ . '/../views/notice/add.view.php';
    }

    public function edit() {
        $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
        if (!$id)die('ID参数缺失');

        $notice = $this->notice->getNoticeById($id);
        if (!$notice)die('公告不存在');

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
            $content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);

            if ($this->notice->editNotice($id, $title, $content)) {
                header('Location: index.php?c=notice&a=index');
                exit;
            }
        }
        require __DIR__ . '/../views/notice/edit.view.php';
    }

    public function delete() {
        $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
        if ($this->notice->deleteNotice($id)) {
            header('Location: ' . BASE_URL . 'index.php?c=notice&a=index');
            exit;
        }
    }
}